//
//  HOLoginViewController.m
//  微度报修
//
//  Created by foguo-mac-1 on 6/16/16.
//  Copyright © 2016 WeiDu. All rights reserved.
//

#import "HOLoginViewController.h"
#import "HOUtils.h"
#import "NSString+MD5Addition.h"
#import "HOConstants.h"
#import "HOUIMgr.h"
#import "HOTabViewController.h"
#import "HOUserInfoDataModule.h"
#import "UIDevice+IdentifierAddition.h"
#import "HOFillInfoViewController.h"
#import "HOStaticDataMgr.h"
#import "HOForgetPWDViewContriller.h"
#import <CommonCrypto/CommonDigest.h>
#import "CompanyEntity.h"
#import "HOSearchCompanyViewController.h"
#import "HOJPushHandler.h"

@interface HOLoginViewController ()
{
	UITextField 		*userNameTextField;
	UITextField 		*passwordTextField;
	UITextField 		*hospitalIDTextField;
	
}
@property(nonatomic, retain)CompanyEntity		*selectedCompany;
@end

@implementation HOLoginViewController
@synthesize needDisplayLeftBtnBarItem;
- (void)viewDidLoad {
    [super viewDidLoad];
	[self initTableView];
	[self initTableViewFooterViewWithTitle:NSLocalizedString(@"登录", @"登录")];
    // Do any additional setup after loading the view from its nib.
	[self initSubviews];
	[self registerKeyboard];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)hideKeyboard
{
	[userNameTextField resignFirstResponder];
	[passwordTextField resignFirstResponder];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
	[self hideKeyboard];
}

- (void)initSubviews
{
//	[self.view setBackgroundColor:[UIColor grayColor]];
//	
//	UILabel *lbl = [[UILabel alloc] init];
//	lbl.frame = CGRectMake(0, 100, self.view.frame.size.width, 30);
//	lbl.text = NSLocalizedString(@"登录", @"登录");
//	lbl.textColor = [UIColor whiteColor];
//	lbl.font = [UIFont systemFontOfSize:25];
//	[self.view addSubview:lbl];
//	lbl.textAlignment = NSTextAlignmentCenter;
	//	[lbl release];
	
	hospitalIDTextField = [[UITextField alloc]
						 initWithFrame:CGRectMake(80,
												  0,
												  self.view.frame.size.width - 170,
												  44)];
	[hospitalIDTextField.layer setMasksToBounds:YES];
	hospitalIDTextField.placeholder = NSLocalizedString(@"请输入5位医院号", @"请输入5位医院ID");
	[hospitalIDTextField setBackgroundColor:[UIColor whiteColor]];
	hospitalIDTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
	hospitalIDTextField.font = [UIFont systemFontOfSize:14];
	hospitalIDTextField.delegate = self;
	hospitalIDTextField.keyboardType = UIKeyboardTypeNumberPad;
	
	userNameTextField = [[UITextField alloc]
						 initWithFrame:CGRectMake(80,
												  0,
												  self.view.frame.size.width - 120,
												  44)];
	[userNameTextField.layer setMasksToBounds:YES];
	userNameTextField.placeholder = NSLocalizedString(@"请输入6-20位的工号", @"请输入6-20位的工号");
	[userNameTextField setBackgroundColor:[UIColor whiteColor]];
	userNameTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
	userNameTextField.font = [UIFont systemFontOfSize:14];
	userNameTextField.delegate = self;
	
	passwordTextField = [[UITextField alloc]
						 initWithFrame:CGRectMake(80,
												  0,
												  self.view.frame.size.width - 170,
												  44)];
	[passwordTextField.layer setMasksToBounds:YES];
	passwordTextField.secureTextEntry = YES;
	passwordTextField.font = [UIFont systemFontOfSize:14];
	passwordTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
	[passwordTextField setBackgroundColor:[UIColor whiteColor]];
	passwordTextField.placeholder = NSLocalizedString(@"请输入6-20位的密码", @"请输入6-20位的密码");
	passwordTextField.delegate = self;
	
#if isTestingMode
	hospitalIDTextField.text = @"00002";
	userNameTextField.text = @"bx_fox";
	passwordTextField.text = @"123456";
#endif
	
}

- (BOOL)textField:(UITextField *) textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
	
	NSUInteger oldLength = [textField.text length];
	NSUInteger replacementLength = [string length];
	NSUInteger rangeLength = range.length;
	
	NSUInteger newLength = oldLength - rangeLength + replacementLength;
	
	BOOL returnKey = [string rangeOfString: @"\n"].location != NSNotFound;
	BOOL result = newLength <= 20 || returnKey;
	if(!result)
	{
		if(textField == userNameTextField)
		{
			[self popupHintView:NSLocalizedString(@"请输入6-20位的工号!", @"请输入6-20位的工号!")];
		}
		else
		{
			[self popupHintView:NSLocalizedString(@"请输入6-20位的密码!", @"请输入6-20位的密码!")];
		}
	}
	return result;
}

- (void)viewWillAppear:(BOOL)animated
{
	self.navigationItem.hidesBackButton = YES;
	self.navigationController.navigationBar.hidden = NO;
	[super viewWillAppear:animated];
	[self setNavigationItemTitle:NSLocalizedString(@"登录", @"登录")];
//	userNameTextField.text = @"bx_user1";
//	passwordTextField.text = @"123456";
}

- (void)didClickFooterButton:(UIButton *)btn
{
	[self hideKeyboard];
	NSString *userName = [self getTrimingCharaFromTextField:userNameTextField];
	NSString *password = [self getTrimingCharaFromTextField:passwordTextField];
	NSString *hospitalID = [self getTrimingCharaFromTextField:hospitalIDTextField];
	
	if(hospitalID.length != 5 && isUnitfiedVersion)
	{
		[self popupHintView:NSLocalizedString(@"请输入5位的医院号!", @"请输入5位的医院号!")];
		return;
	}
	if(userName.length < 6 || userName.length > 20)
	{
		[self popupHintView:NSLocalizedString(@"请输入6-20位的工号!", @"请输入6-20位的工号!")];
		return;
	}
	if(password.length < 6 || password.length > 20)
	{
		[self popupHintView:NSLocalizedString(@"请输入6-20位的密码!", @"请输入6-20位的密码!")];
		return;
	}
	
	UIDevice *device = [UIDevice currentDevice];
	NSString *deviceID = [device uniqueDeviceIdentifier] == nil ? @"" : [device uniqueDeviceIdentifier];
	
	NSString *pwd = [self sha256HashFor:password];
	
	NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:@{kHO_FIELD_Action:kHO_ACTION_Login,
																			   kHO_FIELD_UserName:userName,
																			   kHO_FIELD_DeviceId:[HOUtils getValideString:deviceID],
																			   kHO_FIELD_Password:[password stringFromMD5],
																			   @"RegistrationID":[[HOJPushHandler sharedInstance] getRegistertationID],
																			   kHO_FIELD_OSType:@"1",
																			   kHO_FIELD_PhoneType:[NSNumber numberWithInt:1],
																			   kHO_FIELD_OSVersion:[device systemVersion],
																			   kHO_FIELD_UserName:userName}];
	if(isUnitfiedVersion)
		[dic setObject:hospitalID forKey:kHO_FIELD_CompanyID];
	[self sendRequestWithParams:dic];
}

-(NSString*)sha256HashFor:(NSString*)input
{
	const char* str = [input UTF8String];
	unsigned char result[CC_SHA256_DIGEST_LENGTH];
	CC_SHA256(str, strlen(str), result);
	
	NSMutableString *ret = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH*2];
	for(int i = 0; i<CC_SHA256_DIGEST_LENGTH; i++)
	{
		[ret appendFormat:@"%02x",result[i]];
	}
	return ret;
}
#pragma mark - -- UITableViewDelegate/UITableViewDataResource implement methods
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	if(isUnitfiedVersion)
		return 3;
    return 2;
}


- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
	if(IS_IPHONE_4_SCREEN)
	{
		return 10;
	}
    return 110;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
	CGFloat height = [self tableView:tableView heightForHeaderInSection:section];
	UIView *view = [[[UIView alloc]
					initWithFrame:CGRectMake(0,
											 0,
											 tableView.frame.size.width,
											 height)] autorelease];
	UIImageView *imgView = [[UIImageView alloc]
							initWithFrame:CGRectMake((tableView.frame.size.width - 64) / 2,
													 (height - 64) / 2,
													 64,
													 64)];
	imgView.image = [UIImage imageNamed:@"morentu"];
	imgView.layer.cornerRadius = 32;
	[imgView.layer setMasksToBounds:YES];
	[view addSubview:imgView];
	imgView.hidden = IS_IPHONE_4_SCREEN;
	[imgView release];
	[view.layer setMasksToBounds:YES];
	return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *AMBaseTableViewCellIdentifier = @"HOTableViewCell";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:AMBaseTableViewCellIdentifier];
    if(cell == nil)
    {
        cell = [[[UITableViewCell alloc]
                initWithStyle:UITableViewCellStyleDefault
                reuseIdentifier: AMBaseTableViewCellIdentifier] autorelease];
	}
	cell.textLabel.font = [UIFont systemFontOfSize:15];
	cell.textLabel.textColor = TEXT_COLOR_181818;
	if(indexPath.row == 0 && isUnitfiedVersion)
	{
		cell.textLabel.text = NSLocalizedString(@"医院号:", @"医院号:");
		
		UIButton *btn = (UIButton *)[cell viewWithTag:117];
		if(btn == nil)
		{
			btn = [[UIButton alloc] initWithFrame:CGRectMake((tableView.frame.size.width - 90),
															 (44 - 30) / 2,
															 80,
															 30)];
			[btn setTitleColor:MAIN_COLOR_NORMAL forState:UIControlStateNormal];
			btn.tag = 117;
			[btn setTitle:NSLocalizedString(@"查找医院号", @"查找医院号") forState:UIControlStateNormal];
			btn.titleLabel.font = [UIFont systemFontOfSize:12];
			btn.layer.borderWidth = [HOUtils defaultOnePixelConversion];
			btn.layer.borderColor = MAIN_COLOR_NORMAL.CGColor;
			btn.layer.cornerRadius = 5;
			[btn addTarget:self action:@selector(gotoSearchCompany:) forControlEvents:UIControlEventTouchUpInside];
			[cell.contentView addSubview:btn];
		}
		if((UITextField *)[cell viewWithTag:115] == nil)
		{
			hospitalIDTextField.tag = 115;
			[cell.contentView addSubview:hospitalIDTextField];
		}
		if(self.selectedCompany)
			hospitalIDTextField.text = self.selectedCompany.companyId;
	}
	else if((indexPath.row == 1 && isUnitfiedVersion)
			|| (indexPath.row == 0 && !isUnitfiedVersion))
	{
		if((UITextField *)[cell viewWithTag:112] == nil)
		{
			userNameTextField.tag = 112;
			[cell.contentView addSubview:userNameTextField];
		}
		cell.textLabel.text = NSLocalizedString(@"账    号:", @"账    号:");
	}
	else if((indexPath.row == 2 && isUnitfiedVersion)
			|| (indexPath.row == 1 && !isUnitfiedVersion))
	{
		
		if((UITextField *)[cell viewWithTag:113] == nil)
		{
			passwordTextField.tag = 113;
			[cell.contentView addSubview:passwordTextField];
			cell.textLabel.text = NSLocalizedString(@"密    码:", @"密    码:");
			
			UIButton *btn = (UIButton *)[cell viewWithTag:114];
			if(btn == nil)
			{
				btn = [[UIButton alloc] initWithFrame:CGRectMake((tableView.frame.size.width - 75),
																 (44 - 30) / 2,
																 65,
																 30)];
				btn.tag = 114;
				[btn setTitleColor:MAIN_COLOR_NORMAL forState:UIControlStateNormal];
				[btn setTitle:NSLocalizedString(@"忘记密码?", @"忘记密码?") forState:UIControlStateNormal];
				btn.titleLabel.font = [UIFont systemFontOfSize:12];
				btn.layer.borderColor = MAIN_COLOR_NORMAL.CGColor;
				btn.layer.borderWidth = [HOUtils defaultOnePixelConversion];
				btn.layer.cornerRadius = 5;
				[btn addTarget:self action:@selector(forgetPwd:) forControlEvents:UIControlEventTouchUpInside];
				[cell.contentView addSubview:btn];
			}
		}
	}
    return cell;
}

- (void)gotoSearchCompany:(id)sender
{
	HOSearchCompanyViewController *viewCtrl = [[HOSearchCompanyViewController alloc] init];
	[self.navigationController pushViewController:viewCtrl animated:YES];
	[viewCtrl release];
}

- (void)forgetPwd:(id)sender
{
	HOForgetPWDViewContriller *viewCtrl = [[HOForgetPWDViewContriller alloc] init];
	[self.navigationController pushViewController:viewCtrl animated:YES];
	[viewCtrl release];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}
#pragma mark - -- tool
- (void)didReceiveCommand:(NSString *)action data:(id)data
{
	if([action isEqualToString:kHO_CMD_SELECDTED_COMPANY])
	{
		self.selectedCompany = data;
		[baseTableview reloadData];
	}
}
- (void)requestDidSuccessWithResponse:(HOBaseResponseEntity *)response
{
	if([response.action isEqualToString:kHO_ACTION_Login])
	{
//		[((HOUserInfoDataModule *)dataModule) saveToken:[response.dataNode objectForKey:kHO_FIELD_Token]];
//		[[HOUIMgr sharedInstance] didLogin];
		[[[HOUIMgr sharedInstance] getController:HO_MODULE_TYPE_APP] sendRequestWithParams:@{kHO_FIELD_Action:kHO_ACTION_UploadJpush,kHO_FIELD_JPushRegisterID:[[HOJPushHandler sharedInstance] getRegistertationID]}];
		
		int ShouldFillInfo = [[response.dataNode objectForKey:kHO_FIELD_ShouldFillInfo] intValue];
		HO_USER_TYPE userType = [[response.dataNode objectForKey:kHO_FIELD_GroupId] intValue];//"GroupId": "1",String型 用户所属组【1:院领导,2:报修人员,3:维修人员】
		int userId = [[response.dataNode objectForKey:kHO_FIELD_UserId] intValue];
		
		HOUserInfoEntity *userInfo = [[HOStaticDataMgr sharedInstance] getUserInfo];
		[userInfo saveType:userType];
		[userInfo saveUserId:userId];
		[self sendCommand:kHO_CMD_Login data:nil];
		HOTabViewController *viewCtrl = [[HOTabViewController alloc] init];
		[self.navigationController pushViewController:viewCtrl animated:YES];
		[viewCtrl release];
	}
}

- (void)dealloc
{
	[hospitalIDTextField release];
	[userNameTextField release];
	[passwordTextField release];
	self.selectedCompany = nil;
	[super dealloc];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
